package com.itheima.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * @author 吴
 * @version V1.0
 * @Description   七牛云对象存储：https://portal.qiniu.com/kodo/bucket
 *                  开发者中心：https://developer.qiniu.com/kodo/1239/java#overwrite-uptoken
 * @Package com.itheima.utils
 * @date 2021/11/23 15:46
 */


/**
 * 七牛云工具类
 */
public class QiniuUtils {
    // 密钥
    public  static String accessKey = "QjxBliy1xDmChhC8yI_UUFrF-GWL2mgWfahrOu1T";
    public  static String secretKey = "RNmm3GSs6QyOUyolOMvMb8RcuenFqPytYYps6KmN";
    // 存储空间名
    public  static String bucket = "health-20211123";

    /**
     * 使用 字符串上传
     * @param filePath  文件地址
     * @param fileName  文件名
     */
    public static void upload2Qiniu(String filePath,String fileName) throws QiniuException {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);

        // 鉴权
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(filePath, fileName, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    }

    /**
     * 使用字节数组上传
     * @param bytes  文件字节
     * @param fileName  文件名
     */
    public static void upload2Qiniu(byte[] bytes, String fileName) throws QiniuException {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(bytes, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName) throws QiniuException {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        Auth auth = Auth.create(accessKey, secretKey);

        String key = fileName;
        BucketManager bucketManager = new BucketManager(auth, cfg);

        bucketManager.delete(bucket, key);

    }
}
